package com.machine.bootstatemachine.service.impl;

import com.machine.bootstatemachine.dao.OrderMapper;
import com.machine.bootstatemachine.domain.Order;
import com.machine.bootstatemachine.enums.OrderEventEnum;
import com.machine.bootstatemachine.enums.OrderStatueEnum;
import com.machine.bootstatemachine.service.OrderService;
import com.machine.bootstatemachine.service.ordermachine.OrderMachineHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author dai
 * @Date 2021/12/27
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMachineHandler orderMachineHandler;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void create(Order order) {
        order.setStatus(OrderStatueEnum.UN_PAY.getStatus());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        orderMapper.insert(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payOrder(Order order) {
        log.info("pay order orderId: {}", order.getOrderId());
        boolean execute = orderMachineHandler.execute(OrderEventEnum.PAY, order, null);
        log.info("pay order result: {}", execute);
    }

    @Override
    public void orderDone(Order order) {
        log.info("order done orderId: {}", order.getOrderId());
        boolean execute = orderMachineHandler.execute(OrderEventEnum.RECEIVE, order, null);
        log.info("order done result: {}", execute);
    }


}
